import tornado.ioloop
import logging
import tornado.web

from tornado.options import parse_command_line, options
from webssh.handler import IndexHandler, WsockHandler
from webssh.settings import (get_app_settings, get_host_keys_settings,
                             get_policy_setting)



def make_handlers(loop, options):
    # 生成一个字典
    host_keys_settings = get_host_keys_settings(options)
    # 对生成的字典数据进行检查！
    policy = get_policy_setting(options, host_keys_settings)

    handlers = [
        #  路由 视图类 视图类参数！ 发送第一个请求  get 是为了渲染页面 post 是为了 建立ssh 连接！
        (r'/', IndexHandler, dict(loop=loop, policy=policy,
                                  host_keys_settings=host_keys_settings)),
        (r'/ws', WsockHandler, dict(loop=loop)),
    ]
    return handlers


def make_app(handlers, app_settings):
    #指定路由地址 第一个参数 路由映射 第二个参数指的是 配置信息
    app = tornado.web.Application(handlers, **app_settings)
    return app


def main():
    # 通过加入命令行参数 --help　可以查看所有选项变量的信息,但是必须加上parse_command_line()
    parse_command_line()
    # IOLoop实例！
    loop = tornado.ioloop.IOLoop.current()
    # app 并配置配置文件！
    app = make_app(make_handlers(loop, options), get_app_settings(options))
    options.address='192.168.43.108'
    app.listen(options.port, options.address)
    print(options.port)
    print(options.address)
    logging.info('Listening on {}:{}'.format(options.address, options.port))
    loop.start()

if __name__ == '__main__':
    main()